package ui.panels;

import ui.components.ShowEmployeeGridPanel;
import entities.Department;
import entities.User;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.util.Calendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import manager.GenericDriver;
import manager.ManagerDriver;
import model.EmployeeTableModel;
import model.ViewDepartmentComboBoxModel;
import ui.windows.RemedySchedulerFrame;
import ui.windows.ViewEmployeeDialog;

public class EmployeeManagementPanel extends javax.swing.JPanel {

    /** Creates new form EmployeeManagementPanel */
    public EmployeeManagementPanel(RemedySchedulerFrame mainFrame) {
        this.mainFrame = mainFrame;
        driver = (ManagerDriver) mainFrame.getDriver();
        genDriver = mainFrame.getGenericDriver();
        initComponents();
        includeModel();
    }

    private void includeModel() {
        roleModel = new DefaultComboBoxModel(roles);
        roleModel.setSelectedItem("All");
        cbRoles.setModel(roleModel);
        levelModel = new DefaultComboBoxModel(levels[0]);
        cbLevels.setModel(levelModel);
        cbLevels.setSelectedIndex(0);

        depModel = new ViewDepartmentComboBoxModel(genDriver.showDepartment());
        depModel.setViewEmployee();
        Department d = new Department();
        d.setDepartmentID(0);
        d.setName("All");
        depModel.addElementAt(0, d);
        depModel.setSelectedItem(d);
        cbDeps.setModel(depModel);

        employeeModel = new EmployeeTableModel(driver.showEmployee());
        employeeTable.setModel(employeeModel);
        employeeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        employeeTable.setFillsViewportHeight(true);
        employeeTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        employeeTable.getTableHeader().setFont(new Font(null, Font.BOLD, 10));
        DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer();
        cellRenderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
        cellRenderer.setBackground(Color.yellow);
        employeeTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        employeeTable.getColumnModel().getColumn(1).setPreferredWidth(180);
        employeeTable.getColumnModel().getColumn(2).setPreferredWidth(210);
        employeeTable.getColumnModel().getColumn(3).setPreferredWidth(80);
        employeeTable.getColumnModel().getColumn(3).setCellRenderer(cellRenderer);
        employeeTable.getColumnModel().getColumn(4).setPreferredWidth(80);
        employeeTable.getColumnModel().getColumn(4).setCellRenderer(cellRenderer);
        employeeTable.getColumnModel().getColumn(5).setPreferredWidth(110);

        showEmployeeGridPanel = new ShowEmployeeGridPanel(mainFrame, this);
        showEmployeeGridPanel.setModel(employeeModel);
        employeeModel.setGridPanel(showEmployeeGridPanel);
        setShowAsList();
        createEmployeePanel = new CreateEmployeePanel(mainFrame, this);
        editEmployeePanel = new EditEmployeePanel(mainFrame, this);

        filter();
        target = 1;
    }

    private void swithAction() {
        int choise = cbActions.getSelectedIndex();
        switchTarget(choise);
        cbActions.setSelectedIndex(0);
    }

    private void switchTarget(int choise) {
        if (target != choise || target == 4 || target == 1) {
            switch (choise) {
                case 0:
                    break;
                case 1:
                    this.remove(viewControl);
                    txtID.setEnabled(true);
                    txtName.setEnabled(true);
                    cbDeps.setEnabled(true);
                    cbRoles.setEnabled(true);
                    cbLevels.setEnabled(true);
                    if (!showAsGrid) {
                        viewControl = new JScrollPane(employeeTable);
                    } else {
                        viewControl = new JScrollPane(showEmployeeGridPanel);
                    }
                    target = 1;
                    this.add(viewControl, BorderLayout.CENTER);
                    this.revalidate();
                    break;
                case 2:
                    this.remove(viewControl);
                    txtID.setEnabled(false);
                    txtName.setEnabled(false);
                    cbDeps.setEnabled(false);
                    cbRoles.setEnabled(false);
                    cbLevels.setEnabled(false);
                    viewControl = new JScrollPane(createEmployeePanel);
                    target = 2;
                    this.add(viewControl, BorderLayout.CENTER);
                    this.revalidate();
                    break;
                case 3:
                    if (selectedUser != null) {
                        txtID.setEnabled(false);
                        txtName.setEnabled(false);
                        cbDeps.setEnabled(false);
                        cbRoles.setEnabled(false);
                        cbLevels.setEnabled(false);
                        this.remove(viewControl);
                        editEmployeePanel.setSelectedEmployee(selectedUser);
                        viewControl = new JScrollPane(editEmployeePanel);
                        this.add(viewControl, BorderLayout.CENTER);
                        this.revalidate();
                        target = 3;
                    } else {
                        JOptionPane.showMessageDialog(null, "You migh select one employee !");
                    }
                    break;
                case 4:
                    new Thread() {

                        @Override
                        public void run() {
                            deleteEmployee();
                        }
                    }.start();
                    break;
            }
        }
    }

    public void showAllEmployee() {
        switchTarget(1);
    }

    public void showCreateEmployee() {
        switchTarget(2);
    }

    public void showEditEmployee() {
        switchTarget(3);
    }

    public boolean createEmployee(User employee) {
        boolean returnVal = driver.insertEmployee(employee);
        if (returnVal) {
            User view = driver.showEmployeeByID(employee.getUserID());
            employeeModel.addElement(view);
        }
        return returnVal;
    }

    public boolean updateEmployee(User employee) {
        boolean returnVal = driver.updateEmployee(employee);
        if (returnVal) {
            employee.setModifiedDate(Calendar.getInstance().getTime());
            selectedUser.setName(employee.getName());
            selectedUser.setDepartmentID(employee.getDepartmentID());
            selectedUser.setDepartmentName(employee.getDepartmentName());
            selectedUser.setRole(employee.getRole());
            selectedUser.setLevel(employee.getLevel());
            selectedUser.setMale(employee.isMale());
            selectedUser.setBirthDate(employee.getBirthDate());
            selectedUser.setPhone(employee.getPhone());
            selectedUser.setEmailAddress(employee.getEmailAddress());
            selectedUser.setAddress(employee.getAddress());
            employeeModel.update(selectedUser);
        }
        return returnVal;
    }

    public void deleteEmployee() {
        if (selectedUser != null) {
            target = 4;
            int choise = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete this employee !", "Delete", JOptionPane.YES_NO_OPTION);
            if (choise == JOptionPane.YES_OPTION) {
                boolean returnVal = driver.deleteEmployee(selectedUser);
                if (returnVal) {
                    employeeModel.removeEmployee(selectedUser);
                    JOptionPane.showMessageDialog(this, "Deleted");
                } else {
                    JOptionPane.showMessageDialog(this, "Cannot delete !", "Error", JOptionPane.WARNING_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "You migh select one employee !", "Message", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public boolean containtID(String id) {
        return employeeModel.containtID(id);
    }

    public void setSelectedEmployeeAction(java.awt.event.MouseEvent evt) {
        int index = employeeTable.getSelectedRow();
        if (index != -1) {
            selectedUser = employeeModel.getAt(index);
            if (evt.getClickCount() == 2) {
                ViewEmployeeDialog dialog = new ViewEmployeeDialog(mainFrame);
                dialog.setSelectedUser(selectedUser);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
            }
        } else {
            selectedUser = null;
        }
        editEmployeePanel.setSelectedEmployee(selectedUser);
    }

    public void setSelectedEmployee(User user) {
        this.selectedUser = user;
        try {
            editEmployeePanel.setSelectedEmployee(selectedUser);
        } catch (Exception e) {
        }
    }

    private void setRole() {
        int choise = cbRoles.getSelectedIndex();
        if (choise != -1) {
            levelModel = new DefaultComboBoxModel(levels[choise]);
            cbLevels.setModel(levelModel);
            cbLevels.setSelectedIndex(0);
        }
    }

    private void setShowAsList() {
        showAsGrid = false;
        showAllEmployee();
        bList.setEnabled(false);
        bGrid.setEnabled(true);
    }

    private void setShowAsGrid() {
        showAsGrid = true;
        showAllEmployee();
        bList.setEnabled(true);
        bGrid.setEnabled(false);
    }

    private void filter() {
        try {
            String id = txtID.getText();
            String name = txtName.getText();
            Department selectedDep = (Department) cbDeps.getSelectedItem();
            int depID = selectedDep.getDepartmentID();
            int role = cbRoles.getSelectedIndex();
            int level = cbLevels.getSelectedIndex();
            employeeModel.filter(id, name, depID, role, level, null, null);
        } catch (Exception e) {
        }
    }

    public void closeTarget() {
        switchTarget(1);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtID = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        cbActions = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cbDeps = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        cbRoles = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        cbLevels = new javax.swing.JComboBox();
        bGrid = new javax.swing.JButton();
        bList = new javax.swing.JButton();
        viewControl = new javax.swing.JScrollPane();
        employeeTable = new javax.swing.JTable();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new java.awt.BorderLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setText("ID:");

        txtID.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtIDCaretUpdate(evt);
            }
        });

        jLabel2.setText("Name:");

        txtName.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtNameCaretUpdate(evt);
            }
        });

        cbActions.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Actions", "View", "Add", "Edit", "Delete" }));
        cbActions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbActionsActionPerformed(evt);
            }
        });

        jLabel3.setText("Department:");

        cbDeps.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbDeps.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbDepsActionPerformed(evt);
            }
        });

        jLabel4.setText("Role:");

        cbRoles.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbRoles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbRolesActionPerformed(evt);
            }
        });

        jLabel5.setText("Level:");

        cbLevels.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbLevels.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbLevelsActionPerformed(evt);
            }
        });

        bGrid.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/list-20.png"))); // NOI18N
        bGrid.setToolTipText("Show items in a grid");
        bGrid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGridActionPerformed(evt);
            }
        });

        bList.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/numbered_list-20.png"))); // NOI18N
        bList.setToolTipText("Show items in a employee list");
        bList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bListActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbDeps, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                        .addComponent(cbActions, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbRoles, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbLevels, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 259, Short.MAX_VALUE)
                        .addComponent(bList)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bGrid)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbActions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(cbDeps, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(bGrid)
                        .addComponent(bList))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(cbRoles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(cbLevels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.PAGE_START);

        viewControl.setBackground(new java.awt.Color(255, 255, 255));

        employeeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        employeeTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                employeeTableMouseClicked(evt);
            }
        });
        viewControl.setViewportView(employeeTable);

        add(viewControl, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

private void txtIDCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtIDCaretUpdate
    filter();
}//GEN-LAST:event_txtIDCaretUpdate

private void txtNameCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtNameCaretUpdate
    filter();
}//GEN-LAST:event_txtNameCaretUpdate

private void cbDepsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbDepsActionPerformed
    filter();
}//GEN-LAST:event_cbDepsActionPerformed

private void cbRolesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbRolesActionPerformed
    setRole();
    filter();
}//GEN-LAST:event_cbRolesActionPerformed

private void cbLevelsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbLevelsActionPerformed
    filter();
}//GEN-LAST:event_cbLevelsActionPerformed

private void cbActionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbActionsActionPerformed
    swithAction();
}//GEN-LAST:event_cbActionsActionPerformed

private void employeeTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_employeeTableMouseClicked
    setSelectedEmployeeAction(evt);
}//GEN-LAST:event_employeeTableMouseClicked

private void bListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bListActionPerformed
    setShowAsList();
}//GEN-LAST:event_bListActionPerformed

private void bGridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGridActionPerformed
    setShowAsGrid();
}//GEN-LAST:event_bGridActionPerformed
    private RemedySchedulerFrame mainFrame;
    private ManagerDriver driver;
    private GenericDriver genDriver;
    private ShowEmployeeGridPanel showEmployeeGridPanel;
    private CreateEmployeePanel createEmployeePanel;
    private EditEmployeePanel editEmployeePanel;
    private EmployeeTableModel employeeModel;
    private ViewDepartmentComboBoxModel depModel;
    private DefaultComboBoxModel roleModel, levelModel;
    private User selectedUser;
    private int target;
    private String[] roles = {"All", "Administractor", "Department Head", "Employee"};
    private String[][] levels = {{""}, {"All", "Head", "Employee"},
        {"All", "Head", "Immediate Head", "Next Immediate Head", "Junior Head "},
        {"All", "Doctor", "Staff"}};
    private boolean showAsGrid;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bGrid;
    private javax.swing.JButton bList;
    private javax.swing.JComboBox cbActions;
    private javax.swing.JComboBox cbDeps;
    private javax.swing.JComboBox cbLevels;
    private javax.swing.JComboBox cbRoles;
    private javax.swing.JTable employeeTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    private javax.swing.JScrollPane viewControl;
    // End of variables declaration//GEN-END:variables
}
